package leetcode_回溯;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 子集II
 * 数组中的元素是重复的
 */
public class _90 {
    public static void main(String[] args) {
        System.out.println(new _90().subsetsWithDup(new int[]{1, 2, 2}));
    }

    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<Integer> tem = new ArrayList<>();
        List<List<Integer>> ans = new ArrayList<>();
        boolean[] used = new boolean[nums.length];
        ans.add(new ArrayList<>(tem));
        Arrays.sort(nums);
        for (int i = 1; i <= nums.length; i++) {
            dfs(nums, 0, i, tem, ans, used);
        }
        return ans;
    }
    public void dfs(int[] nums, int begin, int k, List<Integer> tem, List<List<Integer>> ans, boolean[] used) {
        if (tem.size() == k) {
            ans.add(new ArrayList<>(tem));
            return;
        }
        for (int i = begin; i < nums.length - (k - tem.size()) + 1; i++) {
            if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
                continue;
            }
            if (!used[i]) {
                tem.add(nums[i]);
                used[i] = true;
                dfs(nums, i + 1, k, tem, ans, used);
                used[i] = false;
                tem.remove(tem.size() - 1);
            }
        }
    }
}
